package handlers

import (
	"encoding/json"
	"fmt"

	"github.com/yjp211/web"

	"mutu/misc/typedef"
)

func PureJson(data interface{}) string {
	jstr, _ := json.Marshal(data)
	val := string(jstr)

	return val
}

func JsonpReturn(ctx *web.Context, data typedef.Dict, err error) string {
	jsonp, ok := ctx.Params["callback"]
	dict := typedef.Dict{}
	if err != nil {
		dict["ok"] = false
		dict["msg"] = err.Error()
		dict["data"] = nil
	} else {
		dict["ok"] = true
		dict["msg"] = ""
		dict["data"] = data
	}

	jstr, _ := json.Marshal(dict)
	val := string(jstr)

	if ok {
		ctx.SetHeader("Content-Type", "text/javascript; charset=UTF-8", true)
		return fmt.Sprintf("%s(%s)", jsonp, val)
	}
	ctx.SetHeader("Content-Type", "application/json; charset=UTF-8", true)

	return val
}
